package com.ld.businesscard_manage.controller.user;

import com.alibaba.excel.EasyExcel;
import com.ld.businesscard_manage.bean.AllCardsExcel;
import com.ld.businesscard_manage.bean.BusinessCard;
import com.ld.businesscard_manage.bean.MyCardsImportExcel;
import com.ld.businesscard_manage.bean.User;
import com.ld.businesscard_manage.listener.MyUploadDataListener;
import com.ld.businesscard_manage.listener.UploadDataListener;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

public class UploadController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			User user = (User) req.getSession().getAttribute("user");
			//产生关键对象upload，该对象用来取数据
			//创建FileItemFactory实例
			FileItemFactory factory = new DiskFileItemFactory();
			//创建ServletFileUpload实例
			ServletFileUpload upload = new ServletFileUpload(factory);
			//把request中的数据装换成FileItem的集合（解析request请求中的数据）
			List<FileItem> files = null;
			try {
				files = upload.parseRequest(req);
			} catch (FileUploadException e) {
				throw new RuntimeException(e);
			}
			//依次操作每一个表单数据
		try {
			for (int i = 0; i < files.size(); i++) {
				FileItem item = files.get(i);
				//判断是普通值还是文件，false表示是文件
					//取到文件名
					if(user.getStatus() == 1){
						EasyExcel.read(item.getInputStream(), BusinessCard.class, new UploadDataListener()).sheet().doRead();
					}else {
						EasyExcel.read(item.getInputStream(), MyCardsImportExcel.class, new MyUploadDataListener(user)).sheet().doRead();
					}
				}
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter writer = resp.getWriter();

			writer.println("<h1>导入成功</h1>");
			if(user.getStatus() == 0){
				writer.println("<a href='/home/myCard.jsp'>返回我的名片管理页面</a>");
			}else {
				writer.println("<a href='/home/manageCard.jsp'>返回名片管理页面</a>");
			}
			writer.flush();
			writer.close();

		} catch (IOException e) {
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter writer = resp.getWriter();

			writer.println("<h1>导入失败,请稍后重试</h1>");
			writer.println("<a href='/home/manageCard.jsp'>返回名片管理页面</a>");
			writer.flush();
			writer.close();
			throw new RuntimeException(e);
		}


	}
}
